const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

const version = require('./package.json').version;
const { APP_ENV } = process.env

const publicPath = APP_ENV === 'local' ? '/' : '/yuantu/h5-app/'

module.exports = {
  entry: {
    version: path.resolve(__dirname, 'src/version'),
    index: path.resolve(__dirname, 'src/index')
  },

  devtool: 'source-map',

  mode: 'development',

  output: {
    filename: `${APP_ENV === 'local' ? '' : `${version}/`}[name].bundle.js`,
    path: __dirname + '/dist',
    publicPath,
    libraryTarget: 'umd',
  },
  resolve: {
    extensions: [
      '.js',
    ]
  },

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
          },
        },
      }
    ],
  },
  plugins: [
    new CleanWebpackPlugin(),
    APP_ENV === 'local' && new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './index.html',
      minify: true,
      chunks: APP_ENV === 'local' ? ['index'] : ['version'],
      APP_ENV: JSON.stringify(APP_ENV)
    }),
    new webpack.DefinePlugin({
      'process.env.APP_ENV': JSON.stringify(APP_ENV)
    })
  ].filter(Boolean),

  externals: [
    { 'react': 'React' },
    { 'react-dom': 'ReactDOM' },
    { '@ytu-mf/h5-common': '@ytu-mf/h5-common' }
  ],

  devServer: {
    historyApiFallback: true,
    port: 9900,
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
    disableHostCheck: true,
    compress: true,
    publicPath: '/',
  }
};
